package com.lhj.springboot.web.exception;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description RestControllerAdvice ControllerAdvice 二者区别 Rest将以JSON格式返回， ControllerAdvice返回页面
 * @Author lhj
 * @Date 2024/7/6 18:11
 */
@RestControllerAdvice
public class LoginValidatedFieldAdvice {
    
    @ExceptionHandler(value = {MethodArgumentNotValidException.class})
    public ResponseEntity<?> handlerLogin(MethodArgumentNotValidException e) {
        boolean hasErrors = e.hasErrors();
        Map<String, Object> errorsMap = new HashMap<>();
        if (hasErrors) {
            List<FieldError> fieldErrors = e.getFieldErrors();
            for (FieldError fieldError : fieldErrors) {
                errorsMap.put(fieldError.getField(), fieldError.getDefaultMessage());
            }
        }
        
        return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(errorsMap);
    }
    
}
